package com.huleyao.gulimall.product.service.impl;

import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.huleyao.common.utils.PageUtils;
import com.huleyao.common.utils.Query;

import com.huleyao.gulimall.product.dao.CategoryDao;
import com.huleyao.gulimall.product.entity.CategoryEntity;
import com.huleyao.gulimall.product.service.CategoryService;


@Service("categoryService")
public class CategoryServiceImpl extends ServiceImpl<CategoryDao, CategoryEntity> implements CategoryService {

    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        IPage<CategoryEntity> page = this.page(
                new Query<CategoryEntity>().getPage(params),
                new QueryWrapper<CategoryEntity>()
        );

        return new PageUtils(page);
    }

    @Override
    public List<CategoryEntity> listWithTree() {
        //查出所有分类
        //null表示没有任何查询条件
        List<CategoryEntity>entities = baseMapper.selectList(null);

        //组装成树形结构
        //1.找到所有的一级分类
        List<CategoryEntity>levelMenus = entities.stream().filter(categoryEntity ->
            categoryEntity.getParentCid()==0
        ).map((menu)->{
            menu.setChildren(getChildrens(menu,entities));
            return menu;
        }).sorted((menu1,menu2)->{
            return menu1.getSort()==0?0:menu1.getSort()-menu2.getSort()==0?0:menu2.getSort();
        }).collect(Collectors.toList());

        return levelMenus;
    }
    //找到各级分类的子分类
    private List<CategoryEntity> getChildrens(CategoryEntity root,List<CategoryEntity> all){
        List<CategoryEntity> children = all.stream().filter(categoryEntity -> {
            return categoryEntity.getParentCid()==root.getCatId();
        }).map(categoryEntity -> {
            //1.找到子菜单,找到后进行返回
            categoryEntity.setChildren(getChildrens(categoryEntity,all));
            return categoryEntity;
        }).sorted((menu1,menu2)->{
            //2.菜单的排序--找到子菜单后进行排序
            return menu1.getSort()==0?0:menu1.getSort()-menu2.getSort()==0?0:menu2.getSort();
        }).collect(Collectors.toList());
        return children;



    }

    /*
    删除菜单
     */
    public void removeMenuByIds(List<Long> list){
        //TODO 1.首先检查是否被其他元素引用当前菜单
        //2.逻辑删除
        //
        baseMapper.deleteBatchIds(list);
    }

}